package lapsnake.model.stmt;

import java.util.ArrayList;
import java.util.Iterator;

import lapsnake.model.bounceback.ScriptNode;
import lapsnake.model.bounceback.StringNode;
import lapsnake.model.data.*;
import lapsnake.model.*;
import lapsnake.model.expr.LapName;
import lapsnake.model.misc.LapArguments;
import lapsnake.py.ast.ASTHelperFactory; import java.beans.PropertyVetoException;

import org.python.antlr.ast.*;

/**Wrapper class with helper functions for FunctionDef nodes*/
public class LapFunctionDef extends LapStatement {
	
	public final SingleChild<LapName> name = new SingleChild<>(this, LapName.class);
	public final SingleChild<LapArguments> args = new SingleChild<>(this, LapArguments.class);
	public final ChildList<LapStatement> body = new ChildList<>(this, LapStatement.class, false);
	public final ChildList<LapExpression> decorators = new ChildList<>(this, LapExpression.class, true);
	

	public LapFunctionDef(PyAST pyAST, ChildField<? super LapFunctionDef> parentField, FunctionDef node) throws PropertyVetoException {
		super(pyAST, parentField, node);
		
		ASTHelperFactory.makeHelper(pyAST, name, node.getInternalNameNode());
		ASTHelperFactory.makeHelper(pyAST, args, node.getInternalArgs());
		ASTHelperFactory.makeHelpers(pyAST, body, node.getInternalBody());
		ASTHelperFactory.makeHelpers(pyAST, decorators, node.getInternalDecorator_list());
		
		buildTextNodes(node);
	}
	
	public LapFunctionDef(PyAST pyAST, ChildList<LapStatement> parentField, String name) throws PropertyVetoException
	{
		super(pyAST, parentField, null);
		new LapName(pyAST, this.name, name);
		new LapArguments(pyAST, args);
		new LapPass(pyAST, body);
		
		//TODO this is a mess
		ArrayList<ScriptNode> list = new ArrayList<>();
		for(LapExpression d : decorators)
		{
			list.add(d);
			new StringNode("\n");
		}
		list.add(new StringNode("def "));
		list.add(this.name.get());
		list.add(this.args.get());
		
		list.add(new StringNode("): \n"));//Note: PyAST terminates function with "):" and the LapArguments has the "(" part...
		
		for (Iterator<LapStatement> iterator = body.iterator(); iterator.hasNext();)
		{
			list.add(iterator.next());
			list.add(new StringNode("\n"));
		}
		
		setTextNodes(list.toArray(new ScriptNode[list.size()]));
	}

	public String getName()
	{
		return name.toString();
	}
	
	public LapStatement[] getBody()
	{
		return body.toArray();
	}
}
